package com.o2o.cleaning.month.platform.ebusiness_plat.tengxunketang

import com.alibaba.fastjson.{JSON, JSONObject}
import com.mongodb.spark.MongoSpark
import com.mongodb.spark.config.ReadConfig
import com.mongodb.spark.rdd.MongoRDD
import com.o2o.utils.Iargs
import org.apache.spark.rdd.RDD
import org.apache.spark.sql._
import org.bson.Document


/**
 * 拉取数据
 *
 * @ Auther: o2o-rd-0044
 * @ Date:   2021/7/6 17:13
 * @ Param:  $param$
 * @ Description:
 */
object MongoDBData {

  def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder()
      .appName(s"${this.getClass.getSimpleName}")
      .config("spark.debug.maxToStringFields", "2000")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.caseSensitive", "true")
      .master("local[*]")
      .getOrCreate()

    val sc = spark.sparkContext
    sc.hadoopConfiguration.set("fs.s3a.access.key", Iargs.OBSACCESS)
    sc.hadoopConfiguration.set("fs.s3a.secret.key", Iargs.OBSSECRET)
    sc.hadoopConfiguration.set("fs.s3a.endpoint", Iargs.OBSENDPOINT)
    sc.setLogLevel("WARN")


    /** *******************重要重要重要重要重要重要 ************************************************************/
    val year = Iargs.YEAR
    val month = Iargs.MONTH
    val timeStamp = Iargs.TIMESAMP
    val platform = "tengxunketang"
    val readUri = "mongodb://root:O2Odata123!@ 192.168.6.83:27017/admin"

    val readDatabase = "Tengxunketang"
    val readCollection = s"tengxun_list_220${month}"

    //拉取数据保存路径
    val resultUrl = s"s3a://o2o-sourcedata-${year}/obs-source-${year}/${month}/${platform}/"

    // 读取MongoDB数据
    val dataRDD: RDD[String] = loadMongoData(spark, readUri, readDatabase, readCollection, timeStamp)

    spark.read.json(dataRDD).repartition(1).write.mode("overwrite").orc(resultUrl)
    //    dataRDD.repartition(1).saveAsTextFile(resultUrl)
  }


  def loadMongoData(spark: SparkSession, readUri: String, readDatabase: String, readCollection: String, timeStamp: String): RDD[String] = {

    val readConfig = ReadConfig(Map("uri" -> readUri, "database" -> readDatabase, "collection" -> readCollection))

    val mongoRDD: MongoRDD[Document] = MongoSpark.load(spark.sparkContext, readConfig)

    val rdd: RDD[String] = mongoRDD.map(line => {
      val nObject: JSONObject = JSON.parseObject(line.toJson())
      nObject.remove("_id")
      nObject.toString
    })

    rdd
  }
}